﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Context;
using NHibernate.Bytecode;
using NHibernate.Tool.hbm2ddl;
using NhConfig.Expression;

namespace NhConfig
{
    class Program
    {
        static void RunQueries(ISession session)
        {
            var queries = new Queries(session);
            ProductShow.Show("Movie directed by Steven", queries.GetMovieDirectorBy("Steven"));
            ProductShow.Show("Movie with Mecekyz", queries.GetMovieWith("Bob"));
            ProductShow.Show("This book:", queries.GetBookByISBN("978-123-45"));
            ProductShow.Show("Cheap products:", queries.GetProductByPrice(0, 200));
            ProductShow.Show("Average movie:", queries.GetAverageMovicePrice());
            var result = queries.GetPageOfProducts(1, 2);
            var heading = string.Format("Page {0} of {1}", result.PageNumber, result.PageCount);
            ProductShow.Show(heading, result.PageOfResult);
        }

        static void Main(string[] args)
        {
            try
            {
                // log4nnet
                var fileStream = File.OpenRead("log4net.config");
                log4net.Config.XmlConfigurator.Configure(fileStream);
                HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize(); 
                var nhConfigFile = "hibernate.cfg.xml";
                var nhConfig = new Configuration().Configure(nhConfigFile);
                //DefaultProxyFactoryFactory fc;
                //var nhConfig = new ConfigurationBuilder().Build();
                var sessinFactory = nhConfig.BuildSessionFactory();
                //var session = sessinFactory.OpenSession();
                //CurrentSessionContext.Bind(session);
                //SchemaExport export = new SchemaExport(nhConfig);
                //export.SetOutputFile("bin.sql").Execute(false, false, false);

                new ExampleDataCreate(sessinFactory).SetupDataBase();
                using(var session = sessinFactory.OpenSession())
                using (var tx = session.BeginTransaction())
                {
                    RunQueries(session);
                    tx.Commit();
                }
            }
            
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            
            Console.WriteLine("Complted!!");


            // test Expression
            NameAndPrice namePrice = new NameAndPrice() { Name = "Mecekyz", Price = 120m };
            LdPerson<NameAndPrice> lp = new LdPerson<NameAndPrice>() { FName = "Zhuo" };
            lp.GetPropertyName(ex => ex.Name);
            // ExpressionLambda.GetPropertyName<NameAndPrice>(namePrice=>namePrice.)
            Console.Read();
        }
    }
}
